package com.weike.wk_android.utils;

import android.content.Context;

import com.trello.rxlifecycle3.android.ActivityEvent;
import com.trello.rxlifecycle3.components.RxActivity;
import com.trello.rxlifecycle3.components.RxFragment;
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity;
import com.trello.rxlifecycle3.components.support.RxFragmentActivity;

import io.reactivex.FlowableTransformer;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 调度类
 */
public class RxHelper {
    /**
     * 添加RxActivity生命绑定，将耗时操作放在IO线程线程中，更新数据放在主线程中
     * @param context
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<T, T> observableIO2Main(final Context context){
        return upstream -> {
            Observable<T> observable = upstream.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());

            return composeContext(context, observable);
        };
    }

    /**
     * 添加RxFragment生命绑定
     * @param fragment
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<T, T> observableIO2Main(final RxFragment fragment) {
        return upstream -> upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).compose(fragment.<T>bindToLifecycle());
    }

    /**
     * 将耗时操作放在IO线程线程中，更新数据放在主线程中
     * @param <T>
     * @return
     */
    public static <T> FlowableTransformer<T, T> flowableIO2Main() {
        return upstream -> upstream
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 添加RxActivity类生命绑定
     * @param context
     * @param observable
     * @param <T>
     * @return
     */
    private static <T> ObservableSource<T> composeContext(Context context, Observable<T> observable) {
        if (context instanceof RxActivity){
            return observable.compose(((RxActivity)context).bindUntilEvent(ActivityEvent.DESTROY));
        } else if (context instanceof RxFragmentActivity) {
            return observable.compose(((RxFragmentActivity)context).bindUntilEvent(ActivityEvent.DESTROY));
        } else if (context instanceof RxAppCompatActivity) {
            return observable.compose(((RxAppCompatActivity)context).bindUntilEvent(ActivityEvent.DESTROY));
        } else {
           return observable;
        }
    }
}
